import time
from PIL import Image
import cv2
# import numpy as np
from ultralytics import YOLO
import logging
# logging.basicConfig(level=logging.INFO)



# cap = cv2.VideoCapture(video_stream_path)
#
# # Loop through the video frames
# while cap.isOpened():
#     # Read a frame from the video
#     success, frame = cap.read()
#
#     if success:
#         # Run YOLOv8 inference on the frame
#         results = model(frame)
#
#         # Visualize the results on the frame
#         annotated_frame = results[0].plot()
#
#         # Display the annotated frame
#         cv2.imshow("YOLOv8 Inference", annotated_frame)
#
#         # Break the loop if 'q' is pressed
#         if cv2.waitKey(1) & 0xFF == ord("q"):
#             break
#     else:
#         # Break the loop if the end of the video is reached
#         break
#
# # Release the video capture object and close the display window
# cap.release()
# cv2.destroyAllWindows()

import multiprocessing as mp
import cv2



def image_put(q, file_path):
    cap = cv2.VideoCapture(file_path)
    if cap.isOpened():
        print('opened')

    while True:
        q.put(cap.read()[1])
        q.get() if q.qsize() > 1 else time.sleep(0.01)

def image_get(q, window_name):
    # cv2.namedWindow(window_name, flags=cv2.WINDOW_FREERATIO)
    model = YOLO('yolov8n-seg.pt')  # load an official model
    i=0
    while True:
        i+=1
        frame = q.get()
        print("1")
        results = model(frame)
        # im_bgr = results.plot()  # BGR-order numpy array
        # im_rgb = Image.fromarray(im_bgr[..., ::-1])  # RGB-order PIL image

        # Show results to screen (in supported environments)
        # r.show()

        # Save results to disk
        # im_rgb.save(f"{i}_res.jpg")
        # im_rgb.show("")

        # # Get the boxes and track IDs
        # boxes = results[0].boxes.xywh.cpu()
        # track_ids = results[0].boxes.id.int().cpu().tolist()
        #
        # # Visualize the results on the frame
        # annotated_frame = results[0].plot()
        #
        # # Plot the tracks
        # for box, track_id in zip(boxes, track_ids):
        #     x, y, w, h = box
        #     track = track_history[track_id]
        #     track.append((float(x), float(y)))  # x, y center point
        #     if len(track) > 30:  # retain 90 tracks for 90 frames
        #         track.pop(0)
        #
        #     # Draw the tracking lines
        #     # points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
        #     points = []
        #     for point in track:
        #         points.extend(point)
        #
        #     points = [[int(x), int(y)] for x, y in points]
        #     points = [[point] for point in points]
        #     cv2.polylines(annotated_frame, [points], isClosed=False, color=(230, 230, 230), thickness=10)

        # Display the annotated frame
        # cv2.imshow("YOLOv8 Tracking", annotated_frame)

        # Break the loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break

        # cv2.imshow(window_name, frame)
        # cv2.waitKey(1)




def run_single_camera():
    # user_name, user_pwd, camera_ip = "admin", "admin123456", "172.20.114.196"
    user_name, user_pwd, camera_ip = "admin", "buaa0707", "192.168.1.103"
    file = "data/suidao.mp4"
    fname = "suidao"
    # user, pwd, ip, channel = "admin", "buaa0707", "192.168.1.103", 1  # 主码流
    user, pwd, ip, channel = "admin", "buaa0707", "192.168.1.103", 2  # 子码流 分辨率低
    file_path = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (user, pwd, ip, channel)  # HIKIVISION new version 2017


    mp.set_start_method(method='spawn')  # init
    queue = mp.Queue(maxsize=2)
    processes = [mp.Process(target=image_put, args=(queue, file_path)),
                 mp.Process(target=image_get, args=(queue, camera_ip))]

    [process.start() for process in processes]
    [process.join() for process in processes]

if __name__=="__main__":
    # # Load the YOLOv8 model
    # model = YOLO('yolov8n.pt')
    # model = YOLO('yolov8n-seg.pt')  # load an official model
    # # model = YOLO('yolov8n-p2.yaml').load('yolov8n.pt')
    # # Open the video file
    # video_path = "../data/suidao.mp4"
    # user, pwd, ip, channel = "admin", "buaa0707", "192.168.1.103", 1  # 主码流
    # # user, pwd, ip, channel = "admin", "buaa0707", "192.168.1.103", 2 # 子码流 分辨率低
    #
    # video_stream_path = "rtsp://%s:%s@%s//Streaming/Channels/%d" % (
    # user, pwd, ip, channel)  # HIKIVISION new version 2017
    run_single_camera()